package com.data.center.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;

@Component
@Slf4j
public class FieldDataManagementUtils {

    // 使用该工具类实现自动核验及标准化的前提：
    // 抛出异常时确定是系统无法自动处理的异常：如不在字典中、无法自动转换

    /**
     * 验证函数是否通过
     *
     * @param functionServiceObject  需要验证的服务对象
     * @param functionClass          服务对象的类
     * @param verifyFieldName        验证函数的名称
     * @param verifyData             验证数据
     * @return  验证结果，true为通过，false为不通过
     * @throws InvocationTargetException 当调用验证函数时抛出异常
     * @throws IllegalAccessException    当访问验证函数时抛出异常
     */
    public static boolean verify(
            Object functionServiceObject,
            Class functionClass,
            String verifyFieldName,
            Object verifyData,
            Class<?>... parameterTypes
    ) throws InvocationTargetException, IllegalAccessException {
        try {
            return (boolean) functionClass.getMethod(verifyFieldName + "Verify", parameterTypes).invoke(functionServiceObject, verifyData);
        } catch (NoSuchMethodException noSuchMethodException) {
            log.info("无法找到verifyFieldName对应检验函数:" + verifyFieldName);
            return true; // 如果找不到对应验证函数，则直接返回通过（说明该键不需要进行验证）
        }
    }

    public static void standardize(
            Object functionServiceObject,
            Class functionClass,
            String standardizeFieldName,
            Object standardizeData,
            Class<?>... parameterTypes
    ) throws InvocationTargetException, IllegalAccessException {
        try {
            functionClass.getMethod(standardizeFieldName + "Standardize", parameterTypes).invoke(functionServiceObject, standardizeData);
        } catch (NoSuchMethodException noSuchMethodException) {
            log.info("无法找到standardizeFieldName对应标准化函数:" + standardizeFieldName);
            // 如果找不到对应验证函数，则直接返回通过（说明该键不需要继续进行标准化）
        }
    }

    public static void setDefault(
            Object functionServiceObject,
            Class functionClass,
            String setDefaultFieldName,
            Object setDefaultData,
            Class<?>... parameterTypes
    ) throws InvocationTargetException, IllegalAccessException {
        try {
            functionClass.getMethod(setDefaultFieldName + "SetDefault", parameterTypes).invoke(functionServiceObject, setDefaultData);
        } catch (NoSuchMethodException noSuchMethodException) {
            log.info("无法找到setDefaultFieldName对应标准化函数:" + setDefaultFieldName);
            // 如果找不到对应设置默认值函数，则说明该键不需要进行设置默认值
        }
    }

}
